package com.marketingcenter.service.impl;

import com.marketingcenter.entity.ThresholdPromotion;
import com.marketingcenter.entity.ThresholdRule;
import com.marketingcenter.repository.ThresholdPromotionRepository;
import com.marketingcenter.service.ThresholdPromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;

/**
 * 满减满赠满返活动服务实现类
 */
@Service
public class ThresholdPromotionServiceImpl extends PromotionServiceImpl<ThresholdPromotion> implements ThresholdPromotionService {

    @Autowired
    private ThresholdPromotionRepository thresholdPromotionRepository;

    @Override
    protected JpaRepository<ThresholdPromotion, Long> getRepository() {
        return thresholdPromotionRepository;
    }

    @Override
    public List<ThresholdPromotion> findByStatus(Integer status) {
        return thresholdPromotionRepository.findByStatus(status);
    }

    @Override
    public List<ThresholdPromotion> findActivePromotions() {
        LocalDateTime now = LocalDateTime.now();
        return thresholdPromotionRepository.findByStartTimeLessThanEqualAndEndTimeGreaterThanEqual(now, now);
    }

    @Override
    public double calculateDiscount(Long promotionId, double orderAmount) {
        ThresholdPromotion promotion = findById(promotionId);
        if (promotion == null || promotion.getStatus() != 1) { // 1表示进行中
            return 0;
        }

        // 根据订单金额匹配最大的优惠规则
        List<ThresholdRule> rules = promotion.getRules();
        if (rules == null || rules.isEmpty()) {
            return 0;
        }

        // 按门槛金额降序排序
        rules.sort(Comparator.comparing(ThresholdRule::getThresholdAmount).reversed());

        // 查找第一个满足门槛的规则
        for (ThresholdRule rule : rules) {
            if (orderAmount >= rule.getThresholdAmount().doubleValue()) {
                return rule.getDiscountAmount().doubleValue();
            }
        }

        return 0;
    }

    @Override
    public boolean checkOrderEligibility(Long promotionId, double orderAmount, String itemIds) {
        ThresholdPromotion promotion = findById(promotionId);
        if (promotion == null || promotion.getStatus() != 1) { // 1表示进行中
            return false;
        }

        // 检查时间是否在有效期内
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(promotion.getStartTime()) || now.isAfter(promotion.getEndTime())) {
            return false;
        }

        // 检查使用范围
        if (promotion.getUseScope() == 2 || promotion.getUseScope() == 3) { // 2-指定商品，3-指定分类
            // 实际实现中需要检查订单中的商品是否在适用范围内
            // 这里仅做简单返回，实际应用中需要解析itemIds并与applicableIds进行比较
        }

        // 检查订单金额是否满足最小门槛
        List<ThresholdRule> rules = promotion.getRules();
        if (rules != null && !rules.isEmpty()) {
            // 查找最小的门槛金额
            double minThreshold = rules.stream()
                    .mapToDouble(rule -> rule.getThresholdAmount().doubleValue())
                    .min()
                    .orElse(0);
            if (orderAmount < minThreshold) {
                return false;
            }
        }

        return true;
    }

}